<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: songaimin@clcw.com.cn  Blog:http://blog.csdn.net/samxx8        |
// +------------------------------------------------------------------------+
//
namespace AuctionCore\Account\Back;
use AuctionCore\System\AuctionException;

/**
 * 后台员工帐号功能类
 * @author       爱民
 */
class Employee extends \AuctionCore\Account\User {

    /**
     * 用户名
     * @var      String
     */
    protected $user_name;

    /**
     * 授权管理功能类
     * @var      int
     */
    protected $auth_object;

    /**
     * 构造,初始化后台auth对象
     * @param    String $user_name    后台登录用户名
     * @return   void
     */
    public function __construct($account_name) {
        $b_auth = new \AuctionCore\Account\Back\Auth();
        $this->auth_object = $b_auth;
        if (is_numeric($account_name)) {
            $info = self::user_info_id($account_name);
            $this->user_name = $info['username'];
        } else {
            $this->user_name = $account_name;
        }
    }

    /**
     * 创建后台员工
     * @param array info [用户名，密码,昵称,手机号,....]
     * @return user_id
     */
    public static function create_emp($info) {

        $fu = new Employee($info['username']);

        if (empty($info['username'])) {
            AuctionException::make_throw('300001');
        }
        if (empty($info['passwd'])) {
            AuctionException::make_throw('300002');
        }

        $b_auth = new \AuctionCore\Account\Back\Auth();
        $auth_db_cfg = $b_auth->get_config();
        $m = M($auth_db_cfg["AUTH_USER"]);

        $info['passwd'] = md5($info['passwd']);
        $now = date("Y-m-d H:i:s", time());
        $info['createtime'] = $now;
        $info['status'] = 0;
        $user_id = $m->add($info);
        if ($user_id && $info['group_id']) {
            //加入组
            $bu = new Employee($user_id);
            $bu->set_group($info['group_id']);
        }
        return $user_id;
    }

    private function _getModel() {
        $auth_db_cfg = $this->auth_object->get_config();
        $m = M($auth_db_cfg["AUTH_USER"]);
        return $m;
    }

    /**
     * 配合属性“用户名”，修改密码
     * 返回:true/false
     *
     *
     * @param    String $new_pwd    新密码
     * @return   boolean
     */
    public function change_password($new_pwd) {

        if (!$this->user_name) {
            AuctionException::make_throw('300003');
        }
        if (empty($new_pwd)) {
            AuctionException::make_throw('300004');
        }

        $m = $this->_getModel();
        $sets = array('passwd' => md5($new_pwd));
        $ok = $m->where(array('username' => $this->user_name))->save($sets);
        return $ok;
    }

    //更新员工信息 [group_id:员工所属组，username:用户名.......等 等 ]
    public function update($info) {
        $detail = $this->user_info();
        $old_group_id = $detail['group_info'][0]['id'];
        if ($info['group_id'] && $old_group_id != $info['group_id']) {
            $this->exgraft_group($old_group_id);
            $this->set_group($info['group_id']);
        }
        $m = $this->_getModel();
        $sets = $info;
        unset($sets['emp_id']);
        $user_name = $this->user_name;

        $ok = $m->where("username='{$user_name}'")->save($sets);
        return $ok;

    }

    /**
     * 检查密码是否正确，检查启用状态，登录或修改密码使用。
     * 返回：用户信息
     * @param    String $pwd    帐号密码
     * @return   Object
     */
    public function check_pwd($pwd) {
        $m = $this->_getModel();
        $info = $m->where(array('username' => $this->user_name))->find();
        if ($info['passwd'] == md5($pwd)) {
            return $info;
        } else {
            return false;
        }
    }

    /**
     * 用户详细
     * @return   Object
     */
    public function user_info() {
        $m = $this->_getModel();
        $user_name = $this->user_name;
        $info = $m->where("username='{$user_name}'")->find();

        if ($info) {
            $info['group_info'] = M()->query("SELECT g.* FROM au_emp_group_access ac LEFT JOIN au_auth_employee_group g ON ac.id=g.id WHERE ac.emp_id='{$info['emp_id']}';");
        }
        return $info;
    }

    /**
     * 用户详细BY id
     * @param $id int 用户ID
     * @return   Object
     */
    public static function user_info_id($id) {
        $m = M("employee");
        $info = $m->find($id);
        return $info;
    }

    /**
     * 员工姓名找id
     * @param $real_name string 员工姓名
     * @return int
     */
    public static function user_info_rela_name($real_name){
        $m = M("employee");
        $info = $m->where("real_name='$real_name'")->getField("emp_id");
        return $info;
    }

    /**
     * 启用帐号
     * @return   void
     */
    public function enable() {
        $m = $this->_getModel();
        $ok = $m->where(array('username' => $this->user_name))->save(array('status' => '0'));
    }

    /**
     * 禁用帐号
     * @return   void
     */
    public function disable() {
        $m = $this->_getModel();
        $ok = $m->where(array('username' => $this->user_name))->save(array('status' => '1'));
    }
    //逻辑删除
    public function del() {
        $m = $this->_getModel();
        $ok = $m->where(array('username' => $this->user_name))->save(array('status' => '-1'));
    }

    /**
     * 设置员工所属分组
     * @param    int $group_id    组id
     * @return   int
     */
    public function set_group($group_id) {
        $emp_info = $this->user_info();
        $group_users = array('emp_id' => $emp_info['emp_id'], 'id' => $group_id);

        $auth_db_cfg = $this->auth_object->get_config();
        $m = M($auth_db_cfg["AUTH_GROUP_ACCESS"]);
        $m->add($group_users);
    }

    /**
     * 员工移出所属分组
     * @param    int $group_id    组id
     * @return   int
     */
    public function exgraft_group($group_id) {
        $user_info = $this->user_info();
        $auth_db_cfg = $this->auth_object->get_config();
        $m = M($auth_db_cfg["AUTH_GROUP_ACCESS"]);
        $where = "emp_id='{$user_info['emp_id']}' and id='{$group_id}'";
        $ok = $m->where($where)->delete();
        return $ok;
    }

    /**
     * 获取用户分组
     * @return   Object
     */
    public function get_groups() {
        $user_info = $this->user_info();
        $uid = $user_info['emp_id'];
        $prefix = C('DB_PREFIX');
        $rows = M()->query("SELECT ac.emp_id,g.id group_id ,g.* FROM `{$prefix}emp_group_access` ac LEFT JOIN {$prefix}auth_employee_group g  ON ac.id = g.id WHERE ac.emp_id = '{$uid}'");
        return $rows;
    }

    /**
     * 获取部门
     * @param $emp_id
     * @return array
     */
    public static function get_emp_group($emp_id) {
        $map = array("emp_id" => $emp_id);
        $arr = M('emp_group_access')->where($map)->select();
        return $arr;
    }

    /**
     * 删除用户
     * @param string $user_name 用户名
     * @return bool
     */
    public static function remove_emp($user_name) {

        if (empty($user_name)) {
            AuctionException::make_throw('300006');
        }

        $b_auth = new \AuctionCore\Account\Back\Auth();
        $e = new self($user_name);
        $info = $e->user_info();
        $emp_id = $info['emp_id'];

        $auth_db_cfg = $b_auth->get_config();
        $m = M($auth_db_cfg["AUTH_USER"]);
        $ok = $m->where("username='" . $user_name . "'")->delete();

        $m = M($auth_db_cfg["GROUP_ACCESS"]);
        $ok = $m->where("emp_id='" . $emp_id . "'")->delete();

        return $ok;
    }

    /**
     * 检查权限
     * @param rule_names string|array  需要验证的规则列表,支持逗号分隔的权限规则或索引数组
     * @return boolean           通过验证返回true;失败返回false
     */
    public function check_auth($rule_names) {
        $user_info = $this->user_info();
        $uid = $user_info['emp_id'];
        $ok = $this->auth_object->check($rule_names, $uid);

        return $ok;
    }

    /**
     * 检查员工权限
     */
    public static function check_emp_auth($rule_names, $uid) {
        $b_auth = new \AuctionCore\Account\Back\Auth();
        return $b_auth->check($rule_names, $uid);
    }

    /**
     * 通过组id获取雇员
     * @param int $group_id
     * @return multitype:|unknown
     */
    public static function get_emp_by_group_or_store($group_id, $store = 0) {
        if ((int) $group_id < 1) {
            return array();
        }
        $map = array();
        $map['e.status'] = array('eq', 0); //状态正常用户
        $map['g.id'] = array('eq', $group_id);
        if (intval($store) > 0) {
            $map['e.store'] = array('eq', $store);
        }
        $prefix = C('DB_PREFIX');
        $list = M('employee')->alias("e")->field("e.emp_id,e.real_name")
            ->join("{$prefix}emp_group_access g ON e.emp_id = g.emp_id")
            ->where($map)->select();
        return $list;
    }

    /**
     *
     * @param $store
     * @param int $group_id
     * @return array
     */
    public static function get_emp_by_store_group($store, $group_id = 0) {
        if ((int) $store < 1) {
            return array();
        }
        $map = array();
        $map['e.store'] = array('eq', (int) $store);
        if ((int) $group_id > 1) {
            $map['g.id'] = array('eq', (int) $group_id);
        }
        $prefix = C('DB_PREFIX');
        $list = M('employee')->alias("e")->field("e.emp_id,e.real_name")
            ->join("LEFT JOIN {$prefix}emp_group_access g ON e.emp_id = g.emp_id")
            ->where($map)->select();
        return $list;
    }

    /**
     * 获取所有员工
     * @return mixed
     */
    public static function get_all() {
        return M('employee')->select();
    }
    /**
    *重置密码
    */
    public function restpwd() {
        $new_pwd['passwd'] =  md5('123456');
        $ok = M('employee')->where(array('username' => $this->user_name))->save($new_pwd);
    }
}